<?php

class Damages_Methods_Request_Edit_FieldsPermissions extends Damages_Methods_Request {

  /**
   *
   * @var Damages_Methods_Data_Permission_Edit[]
   */
  public $permissions = array();

  public function __construct($params) {
    parent::__construct($params);
    if ($params->permissions)
      foreach ($params->permissions->toArray() as $permission) {
        $permissionObj = new Damages_Methods_Data_Permission_Edit($permission);
        $permissionObj->setFields($permission);
        $permissionObj->setFilters($permission);
        $this->permissions[] = $permissionObj;
      }
  }

  public function process() {
    $con = Propel::getConnection(Damages_Config::getInstance()->datasource);
    $adminId = DamagesPermissionsQuery::create()->filterByCode('ADM')->findOne()->getId();
    $con->beginTransaction();
    try {
      DamagesPermissionListFieldsQuery::create()
              ->filterByPermissionId($adminId, Criteria::NOT_EQUAL)
              ->delete();
      DamagesPermissionListFiltersQuery::create()
              ->filterByPermissionId($adminId, Criteria::NOT_EQUAL)
              ->delete();
      if ($this->permissions)
        foreach ($this->permissions as $permission) {
          if ($permission->fields)
            foreach ($permission->fields as $field) {
              $permissionListField = new DamagesPermissionListFields();
              $permissionListField->setListFieldId($field->id);
              $permissionListField->setPermissionId($permission->id);
              $permissionListField->save();
            }
          if ($permission->filters)
            foreach ($permission->filters as $filter) {
              $permissionListFilter = new DamagesPermissionListFilters();
              $permissionListFilter->setListFilterId($filter->id);
              $permissionListFilter->setPermissionId($permission->id);
              $permissionListFilter->save();
            }
        }
      $con->commit();
    } catch (Exception $exc) {
      $con->rollBack();
      throw $exc;
    }

    $response = new Damages_Methods_Response_GetPermissionManagmentData(true);
    $response->setPermissions();
    return $response;
  }

}